//
//  WithdrawViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/11/1.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "WithdrawViewController.h"
#import "WeChatLoginViewController.h"
@interface WithdrawViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UILabel * accountMoneyContentLab;//账户余额
@property (nonatomic, strong)UITextField * withdrawTextField;//提现金具体金额
@property (nonatomic, assign) BOOL isHaveDian;
@property (nonatomic, assign) BOOL isFirstZero;
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)changeTheSpecifiedString:(NSString *)specifiedString andSpecifiedCharacters:(NSArray *)characters andFont:(NSInteger)fontSize andTheLabel:(UILabel *)specifiedLab;//钱数字体不同大小
- (void)ifLogin;
@end

@implementation WithdrawViewController(networking)
//显示账户余额
- (void)showAccountMoney{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"authiosApi/forward" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            if ([responseObject[@"list"][@"presented"] isEqualToString:@""] || responseObject[@"list"][@"presented"] == nil || [responseObject[@"list"][@"presented"] length] == 0) {
                self.accountMoneyContentLab.text = @"￥  ";
            }else{
                NSString * totalMoney = responseObject[@"list"][@"presented"];
                self.accountMoneyContentLab.text = [NSString stringWithFormat:@"￥  %@", totalMoney];
                [self changeTheSpecifiedString:self.accountMoneyContentLab.text andSpecifiedCharacters:@[@"￥"] andFont:16 andTheLabel:self.accountMoneyContentLab];
            }
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//立即提现
- (void)withdrawMoney{
    NSDictionary * dic = @{
                           @"presented":self.withdrawTextField.text,
                           @"token":self.tokenString,
                           @"phone":self.phoneString
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"authiosApi/forwarddo" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            ShowMessage(responseObject[@"msg"]);
            int64_t delayInSeconds = 1;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation WithdrawViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"提现";
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    [self setUpViews];
    [self showAccountMoney];//网络接口
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 100/WIDTH_6_SCALE;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT)];
        //红色背景图片
        UIImageView * topBGView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 178/WIDTH_6_SCALE)];
        topBGView.image = [UIImage imageNamed:@"withdraw"];
        [_headerView addSubview:topBGView];
        //立即提现
        UIButton * withdrawBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2 + 50/WIDTH_6_SCALE, 161/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        withdrawBtn.centerX = SCREEN_WIDTH/2;
        [self button:withdrawBtn withBGColor:getColor(@"221815") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:4 withMasksToBounds:YES withViwe:_headerView];
        [withdrawBtn setTitle:@"立即提现" forState:UIControlStateNormal];
        withdrawBtn.titleLabel.font = DEF_FontSize_14;
        [withdrawBtn addTarget:self action:@selector(withdrawBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //当前账户余额
        UILabel * accountMoneyTitleLab = [[UILabel alloc] init];
        [self label:accountMoneyTitleLab withFont:DEF_FontSize_12 withText:@"当前账户余额" withTextColor:[UIColor whiteColor] withTextAlignment:NSTextAlignmentCenter withView:topBGView];
        accountMoneyTitleLab.backgroundColor = [UIColor clearColor];
        //金币图案
        UIImageView * goldImg = [[UIImageView alloc] init];
        goldImg.image = [UIImage imageNamed:@"gold"];
        [topBGView addSubview:goldImg];
        //账户具体余额
        self.accountMoneyContentLab = [[UILabel alloc] init];
        [self label:self.accountMoneyContentLab withFont:[UIFont systemFontOfSize:30] withText:[NSString stringWithFormat:@"￥  %@", @"---"] withTextColor:getColor(@"ffe6cf") withTextAlignment:NSTextAlignmentCenter withView:topBGView];
        self.accountMoneyContentLab.backgroundColor = [UIColor clearColor];
        [self changeTheSpecifiedString:self.accountMoneyContentLab.text andSpecifiedCharacters:@[@"￥"] andFont:16 andTheLabel:self.accountMoneyContentLab];
        //提现金具体金额
        self.withdrawTextField = [[UITextField alloc] init];
        self.withdrawTextField.placeholder = @"￥可提金额为100的整数倍";
        self.withdrawTextField.layer.cornerRadius = 4;
        self.withdrawTextField.layer.masksToBounds = YES;
        self.withdrawTextField.font = DEF_FontSize_14;
        self.withdrawTextField.backgroundColor = [UIColor whiteColor];
        self.withdrawTextField.userInteractionEnabled = YES;
        self.withdrawTextField.delegate = self;
        self.withdrawTextField.textAlignment = NSTextAlignmentCenter;
        self.withdrawTextField.clearButtonMode = UITextFieldViewModeAlways;
        self.withdrawTextField.keyboardType = UIKeyboardTypeNumberPad;
        [_headerView addSubview:self.withdrawTextField];
        //手续费说明
        UILabel * serviceChargeLab = [[UILabel alloc] init];
        [self label:serviceChargeLab withFont:DEF_FontSize_10 withText:@"每次提现收取手续费2%" withTextColor:getColor(@"ffe6cf") withTextAlignment:NSTextAlignmentCenter withView:topBGView];
        //masonry
        __weak typeof (self)weakSelf = self;
        [accountMoneyTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topBGView.mas_top).mas_offset(32/WIDTH_6_SCALE);
            make.centerX.equalTo(topBGView.mas_centerX);
        }];
        [goldImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(accountMoneyTitleLab.mas_right).mas_offset(5/WIDTH_6_SCALE);
            make.width.height.mas_offset(15/WIDTH_6_SCALE);
            make.centerY.equalTo(accountMoneyTitleLab.mas_centerY);
        }];
        [self.accountMoneyContentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(topBGView);
            make.top.equalTo(accountMoneyTitleLab.mas_bottom).mas_offset(23/WIDTH_6_SCALE);
        }];
        [self.withdrawTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(topBGView.mas_centerX);
            make.width.mas_offset(250/WIDTH_6_SCALE);
            make.height.mas_offset(30/WIDTH_6_SCALE);
            make.top.equalTo(weakSelf.accountMoneyContentLab.mas_bottom).mas_offset(10/WIDTH_6_SCALE);
        }];
        [serviceChargeLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.headerView);
            make.top.equalTo(weakSelf.withdrawTextField.mas_bottom).mas_offset(10/WIDTH_6_SCALE);
        }];
    }return _headerView;
}
- (void)setUpViews{
    [self.view addSubview:self.tableView];
}
- (void)withdrawBtnClick:(UIButton *)sender{
    NSLog(@"立即提现");
    int withdrawMoney = (int)[self.withdrawTextField.text integerValue];
    if (withdrawMoney < 100) {
        ShowMessage(@"可提金额必须大于100");
    }else if ((withdrawMoney % 100) == nil){
        NSLog(@"成功");
        [self withdrawMoney];
    }else if ((withdrawMoney % 100) != 0){
        ShowMessage(@"可提金额需为100的整数倍");
    }else{
        NSLog(@"成功");
        [self withdrawMoney];
    }
}
#pragma mark - textfieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.withdrawTextField) {
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            _isHaveDian = NO;
        }
        if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
            _isFirstZero = NO;
        }
        if ([string length]>0){
            unichar single=[string characterAtIndex:0];//当前输入的字符
            //数据格式正确
            if (single == '.') {
                return NO;
            }
            if ((single >='0' && single<='9') || single=='.'){
                if([textField.text length]==0){
                    if(single == '.'){
                        //首字母不能为小数点
                        return NO;
                    }
                    if (single == '0') {
                        _isFirstZero = YES;
                        return NO;
                    }
                }
                if (single=='.'){
                    //text中还没有小数点
                    if(!_isHaveDian){
                        _isHaveDian=YES;
                        return YES;
                    }else{
                        return NO;
                    }
                }else if(single=='0'){
                    if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
                        //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                        if([textField.text isEqualToString:@"0.0"]){
                            return NO;
                        }
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=(int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if (_isFirstZero&&!_isHaveDian){
                        //首位有0没.不能再输入0
                        return NO;
                    }else{
                        return YES;
                    }
                }else{
                    if (_isHaveDian){
                        //存在小数点，保留两位小数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt= (int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if(_isFirstZero&&!_isHaveDian){
                        //首位有0没点
                        return NO;
                    }else{
                        return YES;
                    }
                }
            }else{
                //输入的数据格式不正确
                return NO;
            }
        }else{
            return YES;
        }
    }return YES;
}
- (void)changeTheSpecifiedString:(NSString *)specifiedString andSpecifiedCharacters:(NSArray *)characters andFont:(NSInteger)fontSize andTheLabel:(UILabel *)specifiedLab{
    NSString * titleString = specifiedString;
    NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc] initWithString:titleString];
    for (NSString * str in characters) {
        NSRange range = [titleString rangeOfString:str];
        [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:range];
    }
    [specifiedLab setAttributedText:attribute];
}
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
